import VGE from '../../VGE';
import { Camera } from './Camera';
import { Misc } from './Misc';

export default class TMapApp {
	static async open(sceneData = {}) {
		try {
			const { sceneUrl, container, cameraParams, homeView, token, loadOptions } = sceneData;

			await VGE.util.findOrCreateDom(container);
			this.TMap = await this.loadScript({ sceneUrl, token });
			const options = Object.assign(
				{ renderOptions: { preserveDrawingBuffer: true } },
				loadOptions
			);
			this.viewer = await new this.TMap.Map(container, options);

			this.homeViewParams = homeView;

			this.camera = new Camera(this.viewer);
			this.misc = new Misc(this.viewer);
			this.camera.flyTo(cameraParams);

			return this.viewer;
		} catch (e) {
			console.log(e.message);
		}
	}

	static async loadScript({ sceneUrl, token }) {
		// 腾讯地图基于cesium，不先加载会将一些资源修改为腾讯地图的资源导致出错
		const iCesium = await getCesiumScript();
		const dom = await VGE.util.findOrCreateDom('testCesiumTestTMap');
		new iCesium.Viewer(dom, {});
		dom.parentNode.removeChild(dom);

		// 加载腾讯地图
		if (window.TMap) return window.TMap;
		return new Promise((resolve, reject) => {
			const script = document.createElement('script');
			window.callback = () => resolve(window.TMap);
			script.src = `${sceneUrl}&key=${token}&callback=callback`;
			script.onerror = reject;
			document.body.appendChild(script);
		});
	}

	static async close() {
		this.viewer?.destroy();
	}
}
TMapApp.viewer = null;
TMapApp.homeViewParams = {};
TMapApp.camera = null;
TMapApp.misc = null;

async function getCesiumScript() {
	if (window.Cesium) return window.Cesium;
	return new Promise((resolve) => {
		const $link = document.createElement('link');
		$link.rel = 'stylesheet';
		window.document.head.appendChild($link);
		$link.href =
			'/graphics-engine/fusion-cdn/npm/supermap/11i/iClient3D/Cesium/Widgets/widgets.css';

		const $script = document.createElement('script');
		window.document.body.appendChild($script);
		$script.src = '/graphics-engine/fusion-cdn/npm/supermap/11i/iClient3D/Cesium/Cesium.js';
		$script.onload = () => resolve(window.Cesium);
	});
}
